<?php
declare (strict_types=1);

namespace app\common\model;

use Exception;
use think\Collection;
use think\facade\Cache;

class AttributeValue extends CommonBase
{
    private const _CACHE_KEY = '%s_attribute_values';

    public function getAllAttributeValue(array $where = []): array
    {
        $cacheKey        = sprintf(self::_CACHE_KEY, $this->connection);
        $attributeValues = Cache::get($cacheKey);
        if (empty($attributeValues)) {
            $attributeValues = $this->where(['is_delete' => config('status.mysql.table_normal')])->select()->toArray();
            Cache::set($cacheKey, $attributeValues,self::CACHE_EXPIRE_TIME);
        }

        $res = [];
        foreach ($attributeValues as $attributeValue) {
            $flag = true;
            foreach ($where as $key => $value) {
                if (is_array($value) && count($value) == 3 && $value[1] == 'in' && is_array($value[2])) {
                    if (!in_array($attributeValue[$value[0]], $value[2])) {
                        $flag = false;
                        break;
                    }
                } else if ($attributeValue[$key] != $value) {
                    $flag = false;
                    break;
                }
            }

            if ($flag) {
                $res[$attributeValue['id']] = $attributeValue;
            }
        }

        return $res;
    }

    public function getAttributeValueList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->order('sort asc')->limit($offset, $limit)->select();
    }

    public function getAttributeValueCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findAttributeValueById(int $id)
    {
        $attributeValues = $this->getAllAttributeValue();
        return $attributeValues[$id] ?? [];
    }

    public function addAttributeValue(array $data): bool
    {
        $data['is_delete'] = config('status.mysql.table_normal');
        return (boolean)$this->save($data) && Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
    }

    public function updateAttributeValue(int $id, array $data): bool
    {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return (boolean)$this->where(['id' => $id])->save($data) && Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
    }

    public function deleteAttributeValue(int $id): bool
    {
        return (boolean)$this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')])&& Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
    }

    /**
     * @throws Exception
     */
    public function batchDeleteAttributeValue(array $ids): bool
    {
        try {
            $this->startTrans();
            foreach ($ids as $id) {
                $this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            }
            $this->commit();
            Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    public function checkAttributeValueIsUsed(array $moduleCodes, int $id): bool
    {

        foreach ($moduleCodes as $moduleCoe) {
            $count = $this->name( 'article_' . $moduleCoe . '_relation_attribute')->where(['attribute_value_id' => $id])->count();
            if ($count) {
                return true;
            }
        }

        return false;
    }

    public function clearAttributeValueCache(): bool
    {
        return Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
    }
}
